package cn.sunshine.comprehensive.observer_mediator;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Description cn.sunshine.comprehensive.observer_mediator
 * @Author Mokairui
 * @Since 2021/12/30
 */
public abstract class SubscribeContext extends Mediator implements Subject {

    protected List<AbstractUser> userList = new ArrayList<>();

    @Override
    public void attach(AbstractUser user) {
        user.setMediator(this);
        userList.add(user);
    }

    @Override
    public void detach(AbstractUser user) {
        userList.remove(user);
    }

    @Override
    public void notify(String message, Predicate<AbstractUser> userPredicate) {
        userList.forEach(it -> {
            if (userPredicate.test(it)) {
                it.update(message);
            }
        });
    }
}
